package com.atguigu.day06;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Flink05_EventTime_WaterMark {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //手动设置WaterMark生成周期的方法
        env.getConfig().setAutoWatermarkInterval(1000);

        env.setParallelism(2);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
//        DataStreamSource<String> streamSource = env.readTextFile("input/sensor.txt");


        //3.将数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //TODO 设置时间戳以及WaterMark
        SingleOutputStreamOperator<WaterSensor> waterSensorSingleOutputStreamOperator = map.assignTimestampsAndWatermarks(
                //时间戳单调增长的WaterMark
//                WatermarkStrategy.<WaterSensor>forMonotonousTimestamps()
                //允许固定延迟的WaterMark 乱序程度为3S
                WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                //TODO 指定事件时间
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs() * 1000;
                    }
                })
        );


        //4.将相同id的数据聚合到一块
//        KeyedStream<WaterSensor, String> keyBy = map.keyBy(WaterSensor::getId);
        KeyedStream<WaterSensor, String> keyBy = waterSensorSingleOutputStreamOperator.keyBy(r -> r.getId());

        //TODO 5.开启一个基于事件时间的滚动窗口，窗口大小为5S
        WindowedStream<WaterSensor, String, TimeWindow> window = keyBy.window(TumblingEventTimeWindows.of(Time.seconds(5)));
        //开启一个基于事件时间的滑动窗口，窗口大小为6s 滑动步长为3s
//        WindowedStream<WaterSensor, String, TimeWindow> window = keyBy.window(SlidingEventTimeWindows.of(Time.seconds(6), Time.seconds(3)));
        //开启一个基于事件时间的会话窗口，会话间隔为3s
//        WindowedStream<WaterSensor, String, TimeWindow> window = keyBy.window(EventTimeSessionWindows.withGap(Time.seconds(3)));

        //计算范围是针对每个分组的每个窗口
        SingleOutputStreamOperator<WaterSensor> sum = window.sum("vc");

        SingleOutputStreamOperator<String> process = window.process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
            @Override
            public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                String msg =
                        "窗口: [" + context.window().getStart() / 1000 + "," + context.window().getEnd() / 1000 + ") 一共有 "
                                + elements.spliterator().estimateSize() + "条数据 ";
                out.collect(msg);
            }

        });

        process.print();
        sum.print();

        env.execute();
    }
}
